import React, { useState, useContext, useEffect } from "react";
import { UserContext } from "../store";
import { Table, Input, InputNumber, Popconfirm, Form, Typography } from "antd";

const EditableCell = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  const inputNode = inputType === "number" ? <InputNumber /> : <Input />;
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{
            margin: 0
          }}
          rules={[
            {
              required: true,
              message: `Please Input ${title}!`
            }
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};

const EditableTable = () => {
  const [form] = Form.useForm();
  const { store, dispatch } = useContext(UserContext);

  const [data, setData] = useState([]);

  const [editingKey, setEditingKey] = useState("");

  const isEditing = (record) => record.key === editingKey;

  useEffect(() => {
    let arr = store.actionItem.actions.map((item, index) => {
      item.key = index;
      return item;
    });

    setData(arr);
  }, []);

  const edit = (record, index) => {
    form.setFieldsValue({
      action: "",
      name: "",
      describe: "",
      ...record
    });
    setEditingKey(record.key);
  };

  const cancel = () => {
    setEditingKey("");
  };

  const save = async (key) => {
    try {
      const row = await form.validateFields();
      const newData = [...data];
      let index = newData.findIndex((item) => key === item.key);
      if (!key) {
        index = -10;
      }
      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, { ...item, ...row });
        setData(newData);
        setEditingKey("");
      } else {
        row.key = new Date().getTime();
        newData.shift();
        newData.push(row);
        setData(newData);
        setEditingKey("");
      }

      let temp = newData.map((item, index) => {
        let { key, ...params } = item;
        return params;
      });
      changeActionItem(temp);
    } catch (errInfo) {
      console.log("Validate Failed:", errInfo);
    }
  };

  const changeActionItem = (temp) => {
    let obj = store.actionItem;
    obj.actions = temp;
    dispatch({
      type: "actionItem",
      actionItem: obj
    });
  };

  const deleteItem = (record, index) => {
    const arr = data.filter((item, index) => {
      return record.action !== item.action;
    });
    changeActionItem(arr);
    setData(arr);
  };
  const columns = [
    {
      title: "操作类型",
      dataIndex: "action",
      width: "25%",
      editable: true
    },
    {
      title: "名称",
      dataIndex: "name",
      width: "15%",
      editable: true
    },
    {
      title: "描述",
      dataIndex: "describe",
      width: "40%",
      editable: true
    },
    {
      title: "操作 | +",
      dataIndex: "operation",
      render: (_, record, index) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <a
              onClick={() => save(record.key)}
              style={{
                marginRight: 8
              }}
            >
              保存
            </a>
            <Popconfirm title="Sure to cancel?" onConfirm={cancel}>
              <a>取消</a>
            </Popconfirm>
          </span>
        ) : (
          <>
            <Typography.Link
              disabled={editingKey !== ""}
              onClick={() => edit(record, index)}
            >
              编辑
            </Typography.Link>
            <a onClick={() => deleteItem(record, index)}>删除</a>
          </>
        );
      }
    }
  ];
  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: col.dataIndex === "age" ? "number" : "text",
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record)
      })
    };
  });
  return (
    <Form form={form} component={false}>
      <Table
        rowKey="key"
        components={{
          body: {
            cell: EditableCell
          }
        }}
        bordered
        dataSource={data}
        columns={mergedColumns}
        rowClassName="editable-row"
        pagination={{
          onChange: cancel
        }}
        onHeaderRow={(columns, index) => {
          return {
            onClick: (e) => {
              if (e.target.innerHTML === "操作 | +") {
                const item = {
                  key: "",
                  action: "",
                  name: "",
                  describe: "",
                  properties: {
                    supportDataAccessTypes: []
                  }
                };
                setData([item, ...data]);
              }
            } // 点击表头行
          };
        }}
      />
    </Form>
  );
};

export default EditableTable;
